package 设计mos.ObserverPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @作者：xie
 * @时间：2022/10/13 15:23
 */
public class main {
    public static void main(String[] args) {
        Subject subjectA=new ConcreteSubject("mobiaoA");
        Observer observerB= new ConcreteObserver("1", subjectA);
        Observer observerX= new ConcreteObserver("2", subjectA);
        Observer observerD= new ConcreteObserver("2", subjectA);



        subjectA.setState("gxl");
    }
}

interface Subject{
    public void Attach(Observer observer);
    public void Detach(Observer observer);
    public void Notify();

    public void setState(String state);
    public String getState();
}

class ConcreteSubject implements Subject{
    private List<Observer> observersList;
    private  String name;
    private  String state;
    public String getState(){
        return state;
    }


    public ConcreteSubject(String name){
        state="wei genxin";
        this.name=name;
        observersList = new ArrayList<>();
    }

    @Override
    public void Attach(Observer observer) {
        observersList.add(observer);
    }

    @Override
    public void Detach(Observer observer) {
        observersList.remove(observer);
    }

    @Override
    public void Notify() {
        for (Observer observer: observersList){
            observer.update();
        }
    }

    @Override
    public void setState(String state) {
        this.state=state;
        System.out.println(name+"d ztaifasheng gaibian "+ state);
        Notify();
    }
}


interface  Observer{
    public void update();
}

class ConcreteObserver implements Observer{
    private String name;
    private Subject subject;
    private  String state;
    public ConcreteObserver(String name,Subject subject){
        this.name=name;
        this.subject=subject;
        subject.Attach(this);
        state=subject.getState();
    }

    @Override
    public void update() {
        System.out.println(name+":sdtz");
        state=subject.getState();
        System.out.println(name+"gaibianhode ztai");
    }
}